package com.tensquare.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

/**
 * Created by WF on 2020/12/22 16:03
 */
@ConfigurationProperties(prefix = "jwt.config")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JwtUtil {
    private String key;         //加密key
    private long ttl;           //到期时间

    /**
     * 创建jwt的token
     * @return
     */
    public String createJwt(String id, String subject, String role){
        //1.设置当前时间
        Date dt = new Date();
        //2.定义过期时间
        Date expirDate = null;
        //3.根据ttl是否有值，再设置到期时间

        //4.开始生成token
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setSubject(subject)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("role", role);
        if(ttl > 0){
            expirDate = new Date(dt.getTime() + ttl);
            jwtBuilder.setExpiration(expirDate);
        }
        return jwtBuilder.compact();
    }

    /**
     * 解析token
     */
    public Claims parseJwt(String token){
        Claims claims = Jwts.parser()
                        .setSigningKey(key)
                        .parseClaimsJws(token)
                        .getBody();
        return claims;
    }
}
